var MongoClient = require('mongodb').MongoClient;

var async = require('async');

var driver = require('./db');

var response = require('./response');

const Url = "mongodb://localhost:27017/demo";

const table = 'friends';

var dbErrorMsg = "数据库连接失败";

// friend database table
// {userid,friends:[{friend_id,frind_name,time:,answer}]}
// answer:是否同意好友申请

function connect(callback){
    driver.connect(callback,Url);
}

var friendDao = {};

// 搜索好友{searchName：searchName}
friendDao.searchFriends = function (param, res) {

    var username = param.searchName;

    var _query = { "username": { '$regex': username, '$options': 'i' } };

    var table = 'users';

    async.waterfall([
        // 连接数据库        
        function (callback){
            driver.connect(callback,Url);
        },
        // 超找
        function (db,callback) {       
            driver.find(db, callback,table, _query);
        }],
        // result
        function (err, result) {
            console.log("resulte");
            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};

// 好友申请{userId,friendId,frined_name}
friendDao.addFriendRequest = function (param, callback) {

    var userId = param.userId;
    var friend_id = param.friendId;
    var frined_name = param.frinedName;


    var time = new Date().getTime();

    var answer = false;
    var newBoolean = param.new;

    connect(function (db) {
        // 查询
        db.collection(Table).find({ "userid": userId }).toArray(function (err, result) {

            if (err) {
                callback({ success: false, error: '查询friends ' + userId + '失败', msg: '查询失败' });
                return;
            }
            if (result.length == 0) {

                // 创建档案
                db.collection('friends').insertOne({
                    "friends": {
                        "friendid": friend_id,
                        "friend_name": frined_name,
                        "time": time,
                        "answer": answer
                    },
                    "userid": userId
                }, function (err, result) {

                    if (err) {
                        callback({ success: false, error: '插入frinds表失败', msg: '添加好友失败' });
                    } else {
                        console.log('success');
                        callback({ success: true, data: result });
                    }
                    db.close();
                });
            } else {
                db.collection(Table).update(
                    { "userid": userId },
                    {
                        "$pull": {
                            "friends": {
                                "friendid": friend_id,
                                "friend_name": frined_name,
                                "time": time,
                                "answer": answer,
                                "new": newBoolean
                            }
                        }
                    },
                    function (err, result) {
                        if (err) {
                            callback({ success: false, error: '好友申请异常', msg: '好友申请异常' });
                        } else {

                            console.log(result);

                            callback({ success: true, data: result });
                        }

                        db.close();
                    }
                );
            }
        });

    });
};

// 同意好友申请{confirm,userId,friendId}
friendDao.confirmFriendRequest = function (param, res) {

    var answer = param.confirm;
    var userId = param.userId;
    var friend_id = param.friendId;

    connect(function (db) {
        // 更新
        db.collection(Table).update(
            { "userid": userId },
            {
                "$pull": {
                    "friends": {
                        "friendid": friend_id,
                        "answer": answer,
                        "new": false
                    }
                }
            },
            function (err, result) {
                if (err) {
                    res.json({ success: false, error: '同意好友申请异常', msg: '同意好友申请异常' });
                } else {

                    console.log(result);

                    res.json({ success: true, data: result });
                }

                db.close();
            }
        );

    });
};

// 获取全部好友{userId：userId}
friendDao.get = function (param, res) {

    var userId = param.userId;

    var _query = { "userid": userId };

    async.waterfall([
        // 连接数据库        
        function (callback){
            driver.connect(callback,Url);
        },
        // 超找
        function (db,callback) {       
            driver.find(db, callback,table, _query);
        }],
        // result
        function (err, result) {
            console.log("resulte");
            if (err) {
                res.json(err);
                return;
            }
            res.json(result);
        }
    );
};

// 删除好友{userID，friendID}
friendDao.delete = function (obj, res) {

    var friendID = obj.friendID;

    var userID = obj.userID;

    connect(function (db) {

        db.collection(Table).update(
            { "userid": userID },
            { "$pull": { "friends": { "friendid": friendID } } },
            function (err, result) {
                if (err) {
                    response.error(res, err, '删除失败');
                } else {
                    response.success(res, result);
                }

                db.close();
            }
        );

    });
};

module.exports = friendDao;

